import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import { getInfo } from '@/api/user'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  routemenu: [],
  leftmenu: JSON.parse(localStorage.getItem('leftmenu'))

}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_ROUTESMENU: (state, routemenu) => {
    state.routemenu = routemenu
  },
  changeLeftmenu(state, leftmenu) {
    state.leftmenu = leftmenu
    // localStorage.setItem('leftmenu', JSON.stringify(leftmenu))
  },
  SET_NAME: (state, name) => {
    state.name = name
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // let accessedRoutes
      getInfo().then(res => {
        var menuArr = res.data.menu
        var name = res.data.user.name
        localStorage.setItem('navMenu', JSON.stringify(res.data.menu))
        commit('SET_NAME', name)
        commit('SET_ROUTESMENU', menuArr)
        commit('SET_ROUTES', constantRoutes)
        resolve(res)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
